package com.grace.controller;

import com.grace.entity.Student;
import com.grace.service.StudentService;
import com.grace.service.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/listStudentServlet")
public class ListStudentServlet extends HttpServlet {

    StudentService studentService = new StudentServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.当前显示第几页
        String sno = request.getParameter("pageNo");
        int pageNo = 1;//默认显示第1页
        if (sno != null) {
            pageNo = Integer.parseInt(sno);
        }
        final int PAGE_SIZE = 4;
        //2.获取要显示的数据集合
        List<Student> students = studentService.getPageStudents(pageNo, PAGE_SIZE);
        //处理总数量问题
        long counts = 0;
        counts = studentService.getCount();
        //处理页数问题
        int pageSize = 0;
        if (counts % PAGE_SIZE == 0) {
            pageSize = (int) counts / PAGE_SIZE;
        } else {
            pageSize = (int) counts / PAGE_SIZE + 1;
        }

        //3.存数据
        request.setAttribute("students", students);
        request.setAttribute("pageNo", pageNo);
        request.setAttribute("counts", counts);
        request.setAttribute("pageSize", pageSize);
        //4.转发数据
        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }
}
